package com.baizhi.controller;

import com.baizhi.common.dto.Product;
import com.baizhi.common.enums.AckCode;
import com.baizhi.common.vo.PageVO;
import com.baizhi.common.vo.R;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 负载均衡方法，解决nacos服务列表选择问题
 */
@RestController
public class UserLoadBalanceController {

    private static final Logger log = LoggerFactory.getLogger(UserLoadBalanceController.class);

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 使用load balance框架来实现服务选择
     * @param userId
     * @return
     * @throws JsonProcessingException
     */
    @GetMapping("/loadbalance/user/{userId}")
    public R invokeFoundDemo(@PathVariable(value = "userId") int userId) throws JsonProcessingException {
        log.info("user  demo....");

        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        params.put("userName", "小张");

        //调用产品服务中的所有的产品列表信息  ribbon来实现的
        String url="http://PRODUCTSERVICE/productList2?page=1&rows=5";

        // 下面的代码太复杂了,能不能简化，使用openfeign来解决

        R forObject = restTemplate.getForObject(url, R.class);
        if (forObject != null && forObject.getCode() == AckCode.SUCCESS.getCode()) {

            //PageVO<Product>
            Object obj = forObject.getData();
            PageVO mp = (PageVO) obj;

            //取得集合数据
            //序列化成json
//            ObjectMapper objectMapper = new ObjectMapper();
//            String productStr = objectMapper.writeValueAsString(mp.get("rows"));
//            //把java对象序列化json，再把json反序列化自己要想的对象
//            List<Product> productList = objectMapper.readValue(productStr, new TypeReference<List<Product>>() {
//            });
//            //打印产品列表信息
//            for (Product p : productList) {
//                System.out.println(p.toString());
//            }

            params.put("data", mp);

            return R.okHasData(params);
        } else {
            return forObject;
        }
    }





}
